from django.shortcuts import render, HttpResponse, redirect, reverse

# Create your views here.
from django.views import View
from django.contrib import auth


class Login(View):
    def get(self, request):
        return render(request, "demo/login.html")

    def post(self, request):
        user = request.POST.get("username")
        pwd = request.POST.get("pwd")
        res = auth.authenticate(request, username=user, password=pwd)
        if res:
            auth.login(request, res)
            return redirect(reverse("demo:demo_login"))
        return HttpResponse("登陆失败")


class Change_pass(View):
    def get(self, request):
        return render(request, "demo/change_pass.html")

    def post(self, request):
        old_pwd = request.POST.get("old_pwd")
        if request.user.check_password(old_pwd):
            new_pwd = request.POST.get("new_pwd")
            if new_pwd == request.POST.get("new_pwd2"):
                request.user.set_password(new_pwd)
                request.user.save()
                return redirect(reverse("demo:demo_logout"))
        return HttpResponse("原密码或新密码不一致")


def change_pass(request):
    old_pwd = request.POST.get("old_pwd")
    if request.user.check_password(old_pwd):
        new_pwd = request.POST.get("new_pwd")
        if new_pwd == request.POST.get("new_pwd2"):
            request.user.set_password(new_pwd)
            return redirect(reverse("demo:demo_logout"))
    return HttpResponse("原密码或新密码不一致")


def logout(request):
    auth.logout(request)
    return redirect(reverse("demo:demo_login"))
